from . import api

from flask import jsonify,request
from app.models import *
import app
import json


@api.route('/')
def index():

    return '<h1 style="color:blue">系统接口的第一个文件</h1>'


@api.route('/login')
def login():

    # 接受 code
    code = request.args.get('code')

    # 向微信服务器发起请求,获取openid
    # https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxe283f6abab5a1f88&secret=03a63bc71876015640f7d4c51d93b68a&js_code='+code+'&grant_type=authorization_code'
    import requests
    # 发起请求,获取响应对象
    response = requests.get(url)

    # 获取响应结果,转dict
    res = response.json()

    data = request.args.to_dict()
    data.pop('code')
    # 获取openid
    data['openid'] = res['openid']


    # 判断数据库中是否已经存在
    ob = Users.query.filter_by(status=0).filter_by(openid = data['openid']).first()
    if not ob:
        # 如果不存在,则添加数据
        # 存入数据库
        user = Users(**data)
        db.session.add(user)
        db.session.commit()

    # 返回数据
    data = {'error':0,'openid':res['openid']}

    return jsonify(data)

# 微信首页 请求地址 api
# http://192.168.81.130:5000/api/list?appkey=&type=bookLibrary
# http://192.168.81.130:5000/api/list?appkey=&type=bookLibrary&keywords=php
@api.route('/list')
def book_index():
    keywords = request.args.get('keywords',None)
    # 检测是否有搜索条件
    if keywords:
        # 有搜索条件
        books = Books.query.filter_by(status=0).filter(Books.title.contains(keywords)).order_by(Books.id.desc())
     

    else:
        # 没有搜索条件
        # 获取所有的图书信息
        books = Books.query.filter_by(status=0).order_by(Books.id.desc()).all()

    data = {'result':[]}
    for x in books:
        arr = {'title':x.title,'isbn13':x.isbn13,'author':x.author,'image':app.SERVER_ROOT+x.image,'publisher':x.publisher,'price':x.price,'qty':x.qty}
        data['result'].append(arr)

    # 返回json
    return jsonify(data)

    # return json.dumps(data)



# http://192.168.81.130:5000/api/book/detail/9787121185632
# 图书详情 api
@api.route('/book/detail/<bookid>')
def book_detail(bookid):
    # 根据书号,获取书籍信息
    book = Books.query.filter_by(status=0).filter_by(isbn13=bookid).first()

    data = {'title':book.title,'isbn13':book.isbn13,
        'author':book.author,'image':app.SERVER_ROOT+book.image,
        'publisher':book.publisher,'price':book.price,'qty':book.qty,
        'summary':book.Recommend,
        'author_intro':book.authorinfo,
        'catalog':book.Catalog,
        'Explain':book.Explain
    }


    return jsonify(data)



# 借阅图书
@api.route('/book/borrow',methods=['POST'])
def book_borrow():
    try:
        # 接收小程序发送的json数据
        data = request.json

        # 判断当前图书数量是否大于0
        book = Books.query.filter_by(status=0).filter_by(isbn13=data['isbn13']).first()
        if book.qty:
            # 存入数据库
            ob = bookBorrow(**data)
            db.session.add(ob)
            db.session.commit()
            # 修改当前图书 可借阅的数量
            book.qty -= 1
            db.session.add(book)
            db.session.commit()

            return jsonify({'error':0,'msg':'借阅成功'})
        else:
            return jsonify({'error':1,'msg':'借阅失败,图书已被借阅'})

    except:
        return jsonify({'error':2,'msg':'借阅失败,请联系相关人员'})


# 获取当前用户的借阅图书信息
@api.route('/get')
def GetUserBorrowAll():
    # 接收openid
    openid = request.args.get('key')
    # print(openid)

    # 获取当前用户的借阅图书信息
    borrow = bookBorrow.query.filter_by(openid=openid).all()
    result = []
    # 判断当前用户是否有借阅信息
    if borrow:
        for x in borrow:
            book = Books.query.filter_by(status=0).filter_by(isbn13=x.isbn13).first()
            arr =  {
                'title':book.title,
                'author':book.author,
                'price':book.price,
                'publisher':book.publisher,
                'qty':book.qty,
                'image':app.SERVER_ROOT+book.image,
                'isbn13':book.isbn13,
                'borrowDate':x.starttime,
                'shouldBackDate':x.endtime,
            }
            result.append(arr)

    data = {'error':0,'msg':'ok','result':result}
    # 返回
    return jsonify(data)